<!--
 * @Author: your name
 * @Date: 2021-02-15 18:40:16
 * @LastEditTime: 2021-05-18 23:03:05
 * @LastEditors: Please set LastEditors
 * @Description: 添加二维码
 * @FilePath: \jianfa-admin\src\page\project-code\code-add\index.vue
-->
<template>
  <Container class="code-edit">
    <Breadcrumb :navList="['项目二维码管理', '编辑二维码']"></Breadcrumb>
    <avue-form
      ref="form"
      v-model="form"
      :option="option"
      @reset-change="emptytChange"
      @submit="submit"
    >
      <template slot-scope="scope" slot="back_img">
        <van-uploader
          preview-size="200px"
          v-model="fileList"
          multiple
          :max-count="1"
          :after-read="selectImg"
          :before-delete="handleRemove"
        />
      </template>
      <template slot-scope="scope" slot="content">
        <mavon-editor
          v-model="form.content"
          ref="md"
          @imgAdd="$imgAdd"
          @imgDel="$imgDel"
          @change="change"
          :subfield="false"
          :toolbars="toolbars"
        />
      </template>
    </avue-form>
  </Container>
</template>

<script>
import { compressImage } from "@/utils/compressImage"; // 图片压缩方法
export default {
  created() {
    const id = this.$route.query.code_id;
    this.getProjectList(id);
  },
  watch: {
    "$route.query.code_id": {
      handler(newId) {
        this.getProjectList(newId);
      }
    }
  },
  data() {
    return {
      fileList: [], //图片列表
      imgPath: "", //上传的图片地址
      form: {
        content: "",
        html: "",
        imgId: "" //背景图片id
      },
      img_file: [], //图片列表
      toolbars: {
        //编辑器配置
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        superscript: true, // 上角标
        subscript: true, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        code: true, // code
        table: true, // 表格
        fullscreen: true, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        htmlcode: true, // 展示html源码
        help: true, // 帮助
        /* 1.3.5 */
        undo: true, // 上一步
        redo: true, // 下一步
        trash: true, // 清空
        save: true, // 保存（触发events中的save事件）
        /* 1.4.2 */
        navigation: true, // 导航目录
        /* 2.1.8 */
        alignleft: true, // 左对齐
        aligncenter: true, // 居中
        alignright: true, // 右对齐
        /* 2.2.1 */
        subfield: true, // 单双栏模式
        preview: true // 预览
      }
    };
  },
  computed: {
    option() {
      return {
        submitText: "保存",
        column: [
          {
            label: "项目名称",
            prop: "code_name",
            tip: "请输入项目名称",
            span: 12,
            rules: [
              {
                required: true,
                message: "请输入项目名称",
                trigger: "change"
              }
            ]
          },
          {
            label: "顶部图片",
            prop: "back_img",
            span: 24,
            formslot: true
          },
          {
            label: "项目内容",
            prop: "content",
            span: 24,
            rules: [
              {
                required: true,
                message: "请输入项目内容",
                trigger: "change"
              }
            ],
            formslot: true
          }
        ]
      };
    }
  },
  methods: {
    async selectImg(file) {
      const {
        code,
        data: { results, imgsInfo }
      } = await this.$api.img.addImg({ photos: [file.file] });
      if (!code) {
        this.form.imgId = results.insertId;
        this.imgPath = imgsInfo[0].imgPath;
      }
    },
    async handleRemove(file) {
      this.fileList = [];
      const { code } = await this.$api.img.delImg({ img_id: this.form.imgId });
      if (!code) {
        this.form.imgId = "";
        this.imgPath = "";
      }
    },
    //获取工程项目列表
    async getProjectList(id) {
      const {
        code,
        data: { results }
      } = await this.$api.code.getCodeList({ id });
      if (!code) {
        this.form.content = results[0].content;
        this.form.code_name = results[0].code_name;
        this.form.imgId = results[0].imgId;
        this.fileList = [{ content: this.IMGPATH + "/" + results[0].img_path }];
      }
    },
    $imgDel(filename) {
      this.img_file.splice(filename[0] - 1, 1, null);
    },
    // 将图片上传到服务器，返回地址替换到md中
    async $imgAdd(pos, $file) {
      // 缓存图片信息
      /*  const config = {
        width: 500, // 压缩后图片的宽
        // height: 140/250*500, // 压缩后图片的高
        quality: 1, // 压缩后图片的清晰度，取值0-1，值越小，所绘制出的图像越模糊
      };
      compressImage($file, config).then((result) => {
        const fileSize = parseFloat(
          parseInt(result.size) / 1024 / 1024
        ).toFixed(2); //获取图片大小 单位M
        if (!+fileSize) {
          this.img_file.push($file);
        } else {
          this.img_file.push(result);
        }
      }); */
      this.img_file.push($file);
    },
    // 上传图片
    async uploadimg() {
      if (!this.img_file.length) return true;
      const {
        code,
        data: { imgsInfo }
      } = await this.$api.common.addImg({ photos: this.img_file });
      if (!code) {
        const filenameLst = [];
        imgsInfo.forEach((item, index) => {
          const file = [];
          file.push(index + 1, this.IMGPATH + "/" + item.imgPath);
          filenameLst.push(file);
        });
        this.$refs.md.$imglst2Url(filenameLst);
        return true;
      } else {
        this.$message.error("服务器错误,图片上传失败");
        return false;
      }
    },
    //富文本输入时,保存html结构
    change(value, render) {
      this.form.html = render;
      this.form.content = value;
    },
    async submit(form, done) {
      const res = await this.uploadimg();
      if (res) {
        // setTimeout(async () => {
        this.form.id = this.$route.query.code_id;
        const { code, msg } = await this.$api.code.editCode(this.form);
        if (!code) {
          this.$message.success(msg);
          done();
          this.$message.success("编辑成功！");
        }
        // }, 3000);
      }
    },
    emptytChange() {
      this.$message.success("清空成功");
    }
  }
};
</script>
<style lang="scss" scoped>
/deep/.code-edit {
  .v-note-panel {
    height: 400px;
  }
  .v-show-content {
    font-size: 12px;
  }
}
</style>
